#!-*- encoding:utf8 -*-
import email
import mimetypes
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
from email.Utils import COMMASPACE, formatdate
import smtplib
import datetime, time
import math, os, urllib

from newosmp.host.models import Host, Product
from newosmp.define import *
from newosmp.util import strategy
from newosmp.users.models import UserProfile
from newosmp.alert.models import Alert
from newosmp.settings import MonitorDb, MonitorDbType


def creatree(id, html, folder_url="", file_url="", flag=True, auth_pids=[]):
    product = Product.objects.all()
    auth_pids = []
    for p in product:
        auth_pids.append(p.id)
    print auth_pids
        
    tree = Product.objects.filter(ppid=id)
    if id == -1:
        html += '<ul id="browser" class="filetree">'
    else:
        html += "<ul>"
    for t in tree:
        #判断是否有子节点
        if not Product.objects.filter(ppid=t.id):
            host = Host.objects.filter(pid=t.id)
            if not t.id in auth_pids:
               return html + '</ul>'
            if host:
                if folder_url == "":
                    html += '<li><span class="folder">%s</span>\n' % (t.name)
                else:
                    html += '<li><span class="folder"><a href="%s%s" >%s</a></span>\n' % (folder_url, t.id, t.name)
                if flag:
                    html += "<ul>"
                    for e in host:
                        if file_url == "":
                            html += '<li><span class="file">%s</span></li>' % (e.hid.ip)
                        else:
                            html += '<li><span class="file"><a href="%s%s">%s</a></span></li>' % (file_url, e.id, e.name)
                    html += "</ul>"
                html += "</li>"
            else:
                if folder_url == "":
                    html += '<li><span class="folder">%s</span></li>\n' % (t.name)
                else:
                    html += '<li><span class="folder"><a href="%s%s">%s</a></span></li>\n' % (folder_url, t.id, t.name)
        else:
            if folder_url == "":
                html += '<li><span class="folder">%s</span>' % (t.name)
            else:
                html += '<li><span class="folder"><a href="%s%s" >%s</a></span>' % (folder_url, t.id, t.name)
#            print t.id, html, folder_url, file_url, flag, auth_pids
            html = creatree(t.id, html, folder_url, file_url, flag, auth_pids)
            html += "</li>\n"
    html += "</ul>\n"
    return html


def sendmail(to, subject, htmlText):

        strFrom = "panxiaodong@baofeng.com"
        strTo = to
        
        authInfo = {}
        server = "mail.baofeng.com"
        user = "yilan_report@baofeng.com"
        passwd = 'yilan@baofeng'

        # 设定root信息
        msgRoot = MIMEMultipart('related')
        msgRoot['Subject'] = subject
        #msgRoot['From'] = strFrom
        msgRoot['From'] = "osmp@baofeng.com"
        msgRoot['To'] = strTo
        msgRoot.add_header("Date", str(datetime.datetime.now()).split('.')[0])

        msgRoot.preamble = "this is a multi-part message in MIME format."

        # Encapsulate the plain and HTML versions of the message body in an
        # 'alternative’ part, so message agents can decide which they want to display.
        msgAlternative = MIMEMultipart('alternative')
        msgRoot.attach(msgAlternative)


        #设定HTML信息
        htmlText = htmlText + "<br /><a href='http://60.28.110.228:1234/'>[OSMP]</a>"
        msgText = MIMEText(htmlText, "html", "utf-8")
        msgAlternative.attach(msgText)


       #发送邮件
        smtp = smtplib.SMTP()
       #设定调试级别，依情况而定
        smtp.set_debuglevel(1)
        smtp.connect(server)
        smtp.login(user, passwd)
        smtp.sendmail(strFrom, strTo, msgRoot.as_string())
        smtp.quit()
        return


def sendmail(frm, to, subject, htmlText, files=[]): 
        strFrom = frm
        strTo = ';'.join(to)
 
        server = "mail.baofeng.com"
        user = "panxiaodong@baofeng.com"
        passwd = 'dawdo_283232'

        msgRoot = MIMEMultipart('related')
        msgRoot['Subject'] = subject
        msgRoot['From'] = "osmp@baofeng.com"
        msgRoot['To'] = strTo
        msgRoot['Date'] = formatdate(localtime=True) 
        msgRoot.preamble = "this is a multi-part message in MIME format."

        msgAlternative = MIMEMultipart('alternative')
        msgRoot.attach(msgAlternative)

        #设定HTML信息
        htmlText = htmlText + "<br /><a href='http://60.28.110.228:1234/'>[OSMP]</a>"
        msgText = MIMEText(htmlText, "html", "utf-8")
        msgAlternative.attach(msgText)

        msgAttach = MIMEMultipart() 
        msgRoot.attach(msgAttach)
        for file in files: 
            part = MIMEBase('application', "octet-stream") 
            part.set_payload(open(file, "rb").read()) 
            Encoders.encode_base64(part) 
            part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file)) 
            msgAttach.attach(part) 
 

        smtp = smtplib.SMTP()
        #smtp.set_debuglevel(1)
        smtp.connect(server)
        smtp.login(user, passwd)
        smtp.sendmail(strFrom, to, msgRoot.as_string())
        smtp.quit()


def pagination(lst_all, page, num=15):
    lst_len = len(lst_all)
    start = (page - 1) * num
    end = page * num
    if start < 0: 
        start = 0
    if end > lst_len:
        end = lst_len
    lst = lst_all[start:end]
    page_num = int(math.ceil(lst_len / float(num)))
    page_lst = []
    if page_num > 1:
        page_lst = xrange(1, page_num + 1)
    return (lst, page_lst, page_num)

def getPage(page, page_num):
    if page > page_num or page < 1:
        #return HttpResponseRedirect("/host")
        return (1, 1)

    page_up = page - 1
    page_down = page + 1
    
    if page == 1:
        page_up = 1

    if page == page_num:
        page_down = page_num
        
    return(page_up, page_down)

########################update host######################
def updateHost(m, data):
    host = m.hid 
    try:
        if int(data) < 0:
            host.status = 'F'
            host.save()
            return False
    except:
         pass
    dct = str2dct(data)
    host = m.hid 
    host.r_cpu_usage = dct['cpu']
    host.r_cpu_core = dct['cpu_cores']
    host.r_mem_usage = dct['memory']
    host.r_load = dct['load']
    host.r_disk = dct['disk'].split('|')[0].split('-')[1]
    host.r_uptime = datetime.datetime.fromtimestamp(int(dct['uptime']))
    host.r_disk_total = dct['disk_total']
    host.r_mem_total = dct['mem_total']
    host.status = 'T'
    print host.id
    host.save()


def createReportTable(table, items, s):
    ret = True
    table_items = []
    if s == 'S' or s == 'A':
        table_items.append("`%s` float(10,3)" % 'all')

    for k in items:
        table_items.append("`%s` float(10,3)" % k)
    table_sql = """
CREATE TABLE `%s` (
   `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT ,
   `timestamp` int(13) unsigned NOT NULL,
   %s,
   PRIMARY KEY (`id`)) 
ENGINE=MYISAM DEFAULT CHARSET=utf8""" % (table, ','.join(table_items))
    print table_sql
    if MonitorDbType == 'MySQL':
        if MonitorDb.executeSql(table_sql) == False:
            ret = False
                
    return ret

########################tpl##############################
def createTplTable(table, tpl):
    ret = True
    table_items = []
    for k in TPL_ITEMS[tpl]:
        table_items.append("`%s` float(10,3)" % k)
    table_sql = """
CREATE TABLE `%s` (
   `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT ,
   `timestamp` int(13) unsigned NOT NULL,
   %s,
   PRIMARY KEY (`id`)) 
ENGINE=MYISAM DEFAULT CHARSET=utf8""" % (table, ','.join(table_items))
    print table_sql
    if MonitorDbType == 'MySQL':
        if MonitorDb.executeSql(table_sql) == False:
            ret = False
                
    return ret

          

def saveTplData(table, tpl, data, timestamp):
    #createTplTable(table, tpl)
    ret = True
    dct = str2dct(data)
    keys = []
    values = []
    for k in  TPL_ITEMS[tpl]:
        keys.append(k)
        values.append(dct.get(k, 0))
    keys.append('timestamp')
    values.append(int(timestamp))

    sql = "insert into %s (%s) values (%s)" % (table, ','.join(["`%s`" % k for k in keys]),
                                ','.join([str(e) for e in values]))
    print "[Save data][%s]" % sql
    if MonitorDbType == 'MySQL':
        if MonitorDb.executeSql(sql) == False:
            ret = False

    return ret


def getTplData(table, items=[], frm=None, to=None):
    ret = True
    now = int(time.time()) 
    if not frm or not to:
        frm = now - 3600 * 24 * 2
        to = now
    if items == []:
        items = "*"
    else:
        items = ','.join(["`%s`" % e for e in items])
    sql = "select `timestamp`*1000, %s from `%s` where `timestamp` > %s and `timestamp` <= %s" % (items, table, frm, to)
    print sql

    if MonitorDbType == 'MySQL':
        ret = MonitorDb.executeSqlRet(sql)
        if not ret:
            ret = False
    
    return ret


def checkTplData(data, stra):
    print "========================="
    tpl = stra.tpl 
    straData = stra.value 
    fun = stra.handle
    if not fun:
        fun = TPL_STRA_DEFAULT[tpl]
    handle = getattr(strategy, fun)
    return  handle(straData, data)
 

def getUserInfoByIDs(ids):
    objs = UserProfile.objects.select_related(depth=1).filter(user__id__in=ids)
    return objs


def alert(mid, gid, info):
    a = Alert.objects.create(mid=mid, type=0, downtime=0)
    a.save()
    info = "%s,%s" % (mid.name, info)
    print "[%s][%s]" % (time.ctime(), info)
    ids = gid.user.split(',')
    userinfo = getUserInfoByIDs(ids)
    user_mobile = []
    user_mail = []
    print userinfo
    for u in userinfo:
        user_mobile.append(u.mobile)
        user_mail.append(u.mail)
    sendAlertMail(info, user_mail)
    sendAlertMobile(info, user_mobile)
    return True


#################### 所有支持的函数 ######################################
def sendAlertMail(info, mails):
    sendmail('panxiaodong@baofeng.com', mails, info, info)

def sendAlertMobile(info, mobiles):
    for mobile in mobiles:
        sendMobile(info, mobile)
        print 'send msg %s ok' % mobile

def sendMail(msg, mail):
    msg = "%s" % msg
    cmd = u"pysend -s  '%s' -t %s -e '%s'" % (msg, mail, msg)
    print cmd.encode('utf-8')
    return os.system(cmd.encode('utf-8'))

def sendMobile(msg, mobile):
    msg = "%s" % msg
    cmd = '''curl 'http://125.39.0.45/sms.php?p=%s&m="%s"' ''' % (mobile, urllib.quote(msg.encode('utf-8')))
    print cmd
    return os.system(cmd)

def sendGtalk(msg, gtalk):
    msg = "%s" % msg
    cmd = u"gsend -t %s -m '%s'" % (gtalk, msg)
    print cmd.encode('utf-8')
    return os.system(cmd.encode('utf-8'))

def sendMsn(msg, msn):
    return True

def str2dct(s):
    dct = {}
    try:
        if s.find(",") < 0 and s.find(":") < 0:
            dct['value'] = float(s)
        else:
            for item in s.split(','):
                (k, v) = item.split(":")
                dct[k] = v
    except:
        raise
    return dct
 
